import React from 'react';
import './ContactList.css';

function ContactList({ peers, selectedPeer, onSelectPeer }) {
  // Determine user status based on lastSeen timestamp
  const getUserStatus = (peer) => {
    if (!peer.lastSeen) return 'offline';

    const now = Date.now();
    const timeSinceLastSeen = now - peer.lastSeen;

    // Online: active within last 30 seconds
    if (timeSinceLastSeen < 30000) return 'online';

    // Away: active within last 5 minutes
    if (timeSinceLastSeen < 300000) return 'away';

    // Offline: no activity for over 5 minutes
    return 'offline';
  };

  const onlineCount = peers.filter(p => getUserStatus(p) === 'online').length;

  return (
    <div className="contact-list">
      <div className="contact-list-header">
        <h2>Contacts</h2>
        <span className="peer-count">{onlineCount} online</span>
      </div>

      <div className="contact-list-content">
        {peers.length === 0 ? (
          <div className="no-peers">
            <p>No peers found</p>
            <small>Waiting for devices on the network...</small>
          </div>
        ) : (
          peers.map(peer => {
            const status = getUserStatus(peer);
            return (
              <div
                key={peer.id}
                className={`contact-item ${selectedPeer?.id === peer.id ? 'selected' : ''}`}
                onClick={() => onSelectPeer(peer)}
              >
                <div className="contact-avatar">
                  {(peer.name || 'U').charAt(0).toUpperCase()}
                </div>
                <div className="contact-info">
                  <div className="contact-name">{peer.name || 'Unknown'}</div>
                  <div className="contact-ip">{peer.ipAddress || 'N/A'}</div>
                </div>
                <div className={`contact-status ${status}`}></div>
              </div>
            );
          })
        )}
      </div>
    </div>
  );
}

export default ContactList;
